<?php

namespace app\modules\api\controllers;

use app\components\API;
use app\components\Api\JMessageApi;
use app\components\Fun;
use app\components\Sms;
use app\components\SmsLingkai;
use app\components\UploadFile;
use app\components\Utility;
use app\models\Jobs;
use app\models\User;
use app\models\Yzm;
use app\models\YzmModel;
use itxq\apidoc\BootstrapApiDoc;
use \yii\web\Controller;
use Yii;

class MemberController extends Controller
{

    public $layout = 'main_m';
    public $enableCsrfValidation = false;


    private function toJson($code, $data = '', $msg = '系统错误')
    {
        API::echo_json($code, $msg);
    }


     /**
     * @apiGroup 用户
     * @api {post} /api/member/login 用户登录
     * @apiParam {string} phone 用户的手机号
     * @apiParam {string} pwd 密码
     * @apiSuccess {string} token 用于验证,需要在需要验证身份的接口Headers上面携带字段为token
      * @apiSuccess {int} type  101表示公司;102表示工厂;103表示个人应聘
     * @apiSuccessExample token 用于验证
     *
     *{"code":0,"data":{"token":"a85be4b06"}}
     */
    public function actionLogin()
    {
        $phone =\Yii::$app->request->post('phone');
        $pwd = \Yii::$app->request->post('pwd');
        $user = User::find()->where([
            'phone' => $phone
        ])->one();
        if (!$user) {
            API::echo_json(1, '用户不存在');
        }
       // var_dump(User::toPassword($pwd), $user->password,$user->phone,$user->id);exit;
        if (User::toPassword($pwd) !== $user->password) {
            API::echo_json(1, '密码输入错误');
        }
      //  Yii::$app->user->login($user, 60 * 60 * 24 * 7);
        $token=$user->login();
        API::echo_json(0, [
            'token'=>$token,
            'username'=>$user->username,
            'head'=>Fun::pImg($user->avatar),
            'type'=>$user->type,
            'phone'=>$user->phone,
            'id'=>$user->id,
          //  'jiguang_id'=>$user->jiguang_id,
          //  'jiguang_pass'=>$user->jiguang_pass,
        ]);
    }


        /**
     * @apiGroup 用户
     * @api {post} /api/member/yzm 获取验证码
     * @apiParam {string} phone 用户的手机号
     * @apiParam {string} type register表示注册使用 retrieve表示找回密码使用
     * @apiSuccessExample 返回
     *
     *{"code":0,
     * "data":"\u4e07\u80fd\u9a8c\u8bc1\u7801\u662f:1234;\u4e34\u65f6\u5173\u95ed\u77ed\u4fe1\u53d1\u9001,\u77ed\u4fe1\u5185\u5bb9\u662f:\u3010\u7f8e\u7b56\u3011\u9a8c\u8bc1\u78019723\uff0c\u60a8\u6b63\u5728\u8fdb\u884c\u7f8e\u7b56\u5e73\u53f0\u7684\u8d26\u53f7\u6ce8\u518c\uff0c\u6709\u6548\u65f6\u95f430\u5206\u949f\u8eab\u4efd\u9a8c\u8bc1\uff0c\u6253\u6b7b\u4e0d\u8981\u544a\u8bc9\u522b\u4eba\u54e6\uff01"}
     * @apiUse ERROR
     */
    public function actionYzm()
    {

//        $request = \Yii::$app->request;
//        var_dump($request->post('phone','')); exit;
        $phone = \Yii::$app->request->post("phone");//$_POST['phone'];
       // var_dump($phone);exit;
        if (!preg_match('/^1[345789]\d{9}$/', $phone)) {
            API::echo_json(1, '手机号码填写错误');
        }
        $resYzm = $this->getYzm($phone);
        if ($resYzm) {
         //   API::echo_json(1, '刚刚已经发送给验证码');
        }
//        $code = Utility::getRandStr(rand(4,6),0);
        $code = Utility::getRandStr(4, 0);
        /// YzmModel::deleted();
        $newyzm = new YzmModel;
        $newyzm->status="1";
        $newyzm->phone = $phone;
        $newyzm->code = $code;
        $newyzm->time = time();
        $newyzm->save();
        ///var_dump($newyzm->getErrors());
        $lastId = $newyzm->id;
        //($dataArr);

        $msg = "验证码{$code}，有效时间".(YzmModel::Maxtime)."秒身份验证，打死不要告诉别人哦！【美策网络】";
      //  $msg="验证码{$code}，打死不要告诉别人哦！【美策网络】";

        $sms = new SmsLingkai();
        $resSms = $sms->sendSMS($phone, $msg);
        $resSms = json_decode($resSms, true);
        if (empty($resSms) || !empty($resSms['errorMsg'])) {
            return $this->toJson(-11);
        }


        $newyzm->status = "2";
        $res=$newyzm->update();
        return $this->toJson(0, [], "ok" );
        /// YzmModel::where('id', $lastId)->update(array('status' => 2));
     //   return $this->toJson(0, [], '万能验证码是:1234;临时关闭短信发送,短信内容是:' . $msg);
    }

    /**
     * 获取验证码
     */
    public function getYzm($phone)
    {
        $model = YzmModel::find()->where('phone=:phone AND status=:status AND time>:time', [
            'phone' => $phone,
            'status' => 2,
            'time' => time() - YzmModel::Maxtime
        ])->one();
        return $model ? $model->code : '';


    }

    /**
     * 重置密码
     */
    public function actionPwd()
    {

    }


    /**
     * @apiGroup 用户
     * @api {post} /api/member/regist 用户注册
     * @apiParam {string} phone 用户的手机号
     * @apiParam {string} yzm 验证码 万能验证码 是1234852963
     * @apiParam {string} pwd 密码
     * @apiSuccess {string} token 用于判断用户登录状态
     * @apiSuccess {string} is_company 是否启用公司
     * @apiSuccess {string} is_factory 是否启用工厂
     * @apiSuccess {string} is_yingpin 是否启用应聘
     * @apiSuccess {string} id  id
     * @apiSuccess {string} username 昵称
     * @apiSuccess {string} phone 手机号码
     * @apiSuccess {string} head 头像
     * @apiSuccessExample 返回
     *
     {"code":0,"data":{"token":"86f40dbdb84ad64fa9df5fdc71100f2d","username2":"\u65b0\u7528\u6237","phone":"15560195088","is_company":0,"is_factory":0,"is_yingpin":0,"id":"5745","head":"http:\/\/test.fuzhuangchangongxiao.cn\/h5\/images\/toux01.png"}}
     *
     * @apiUse ERROR
     * @apiError -7 验证码错误
     * @apiError -8 手机号码不符合要求
     * @apiError -12 密码设置不符合要求
     * @apiError -4 该手机已经注册过了
     */
    public function actionRegist()
    {
        $phone =\Yii::$app->request->post('phone');
        $pwd =\Yii::$app->request->post('pwd');
        $yzm = \Yii::$app->request->post('yzm');
        if (!$phone || !$pwd || !$yzm) {
            return $this->toJson(-2,[],'参数错误');
        }

        if ($yzm != '1234852963') {
            //验证码校验
            $resYzm = $this->getYzm($phone);
            if (!$resYzm || $yzm !== $resYzm) {
                return $this->toJson(-7,[],'验证码错误');
            }
        }
        if (!preg_match('/^1[3456789]\d{9}$/', $phone)) {
            return $this->toJson(-8,[],'手机号码不符合要求');
        }
        if (!preg_match('/^[0-9a-zA-Z_]{5,20}$/', $pwd)) {
            return $this->toJson(-12,[],'密码设置不符合要求');
        }
        $model =User::find()->where([
            'phone'=>$phone
        ])->one();
        if ($model) {
             return $this->toJson(-4,[],'该手机已经注册过了');
        }
        //保存信息
        $nameStr = '新用户';
        $pwdHash = User::toPassword($pwd);
        $Jiguang_pass=md5($pwdHash.time());
        $jiguang_id=JMessageApi::getRandChar();
        $user=new User;
        $user->username=$nameStr;
        $user->phone=$phone;
        $user->password=$pwdHash;
        $user->jiguang_id=$jiguang_id;
        $user->jiguang_pass=$Jiguang_pass;
        $user->is_company=0;
        $user->is_factory=0;
        $user->is_yingpin=0;
        $user->avatar=Fun::pImg(User::defaultHead);
        if($user->save()===false){
            return $this->toJson(-3,[],'系统错误');
        }
        $lastId=$user->id;
        $token=$user->login();///实现用户登录
       // Yii::$app->user->login($user);
        //生成token
       /// $token = $this->accessSet($lastId);
        ///
        $userModel=new User;
        JMessageApi::register($jiguang_id,$Jiguang_pass);
        JMessageApi::upNameNick($jiguang_id,$nameStr);
        $resArr = array(
            'token'=>$token,
            'username'=>$nameStr,
            'phone'=>$phone,
            'is_company'=>0,
            'is_factory'=>0,
            'is_yingpin'=>0,
            'id'=>$lastId,
            'head'=> Fun::pImg($user->avatar)
        );

        //记录用户须知
      //  $this->userService->setUserNotice($lastId);

        return  $this->toJson(0,[], $resArr);///)->cookie('token',$token, 60*24*7);
    }


    /**
     * @apiGroup 系统
     * @api {post} /api/member/uploadimg 文件上传,如果一个图片重复上传,返回的结果相同
     * @apiParam {file} img 上传的图片数据
     * @apiSuccess {string} data.img 返回的图片链接地址, http://***small.jpg 表示压缩后的小图,如果替换成big.jpg表示大图
     * @apiSuccessExample 返回
     * {"code":0,"data":{"img":"http:\/\/test.fuzhuangchangongxiao.cn\/public\/Uploads\/image\/20200730\/20200730112333_33821small.jpg"}}
     */
    public function actionUploadimg(){

        header("Access-Control-Allow-Origin: *");
     /*   if(Yii::$app->user->isGuest){
            API::echo_json(1,API::guest);///如果是游客用户,直接退出
        }*/
        $url=UploadFile::start("img");

        API::echo_json(0,$url);
    }

}
